package cn.kgc.springcloud.controller;

import cn.kgc.springcloud.entity.Clazz;
import cn.kgc.springcloud.service.ClazzService;
import cn.kgc.springcloud.vo.ClazzVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author: mosin
 * @version: v1.0  2022/8/28
 */
@RestController
@RequestMapping("clazz")
public class ClazzController {

    @Autowired
    private ClazzService clazzService;
    @PostMapping
    public Clazz addClazz(MultipartFile file ,String name,Integer tagId){

        if(file==null){
            throw  new RuntimeException("文件不能为空");
        }

        // 获取文件的名字
        String originalFilename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //获取文件的扩展名
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        //拼接文件上传的名字
        String finalName = uuid+"."+filenameExtension;
        //文件上传
        try {

            file.transferTo(new File("D:\\upload", finalName));
            // name  tagId  path
            Clazz clazz = new Clazz();
            clazz.setTagId(tagId);
            clazz.setName(name);
            clazz.setPath(finalName);
            Clazz clzz = clazzService.addClazz(clazz);
            return  clzz;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @GetMapping
    public List<ClazzVO> clazzList(){

        List<ClazzVO> clazzVOS =  clazzService.findAll();
        return clazzVOS;
    }


    @DeleteMapping("{clazzId}")
    public Boolean deleteClazz(@PathVariable Integer clazzId){
       Boolean b =   clazzService.deleteClazz(clazzId);
        return  b ;
    }

    @GetMapping("{clazzId}")
    public Clazz getById(@PathVariable Integer clazzId){
      Clazz clazz =   clazzService.selectById(clazzId);
      return  clazz;
    }
}
